package com.harboursoftware.xstorage.operations;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.ListMultimap;
import com.harboursoftware.xstorage.XStorageException;
import com.harboursoftware.xstorage.ac.AccessControlPolicy;
import com.harboursoftware.xstorage.ac.Permission;
import com.harboursoftware.xstorage.fs.BucketNotExistException;
import com.harboursoftware.xstorage.fs.ObjectNotExistException;
import com.harboursoftware.xstorage.model.XBucket;
import com.harboursoftware.xstorage.model.XElement;
import com.harboursoftware.xstorage.model.XObject;
import com.harboursoftware.xstorage.model.XUser;
import com.harboursoftware.xstorage.results.EmptyContentResult;
import com.harboursoftware.xstorage.results.ErrorResult;
import com.harboursoftware.xstorage.results.Result;

public class DeleteObject extends Operation {
    private final static Logger log = LoggerFactory.getLogger(DeleteObject.class);
    @Override
    public Result execute(XUser requester, XElement element, ListMultimap<String, String> headers, Map<String, String> parameters) {
        log.debug("execute");
        XObject object = (XObject)element;
        XBucket bucket = object.getBucket();
        try {
            fileSystem.loadBucketACP(bucket);
            AccessControlPolicy bucketAcp = bucket.getAcp();
            if(!bucketAcp.checkPermission(requester, getRequiredPermission())) {
                //TODO : 权限处理
            }
            fileSystem.deleteObject(object);
        } catch (BucketNotExistException e1) {
            return ErrorResult.create(ErrorResult.Type.NO_SUCH_BUCKET);
        } catch (ObjectNotExistException e1) {
            return ErrorResult.create(ErrorResult.Type.NO_SUCH_KEY);
        } catch (XStorageException e) {
            log.error("error occured when delete object", e);
            return ErrorResult.create(ErrorResult.Type.NO_SUCH_KEY);
        }
        return new  EmptyContentResult(204);
    }
    @Override
    public Permission getRequiredPermission() {
        return Permission.WRITE;
    }

}
